package com.rtp2p.rtcoresdkdemo.base

import android.content.Context
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView

class BaseRecyclerView {
    abstract class BaseAdapter<T, VH : RecyclerView.ViewHolder?> : RecyclerView.Adapter<VH>() {
        private val datas = mutableListOf<T>()

        override fun getItemCount(): Int {
            return datas.size
        }

        fun onRefreshData(list: List<T>) {
            if (!datas.isEmpty()) datas.clear()
            datas.addAll(list)
            notifyDataSetChanged()
        }

        fun add(index:Int,data: T){
            datas.add(index,data)
            notifyDataSetChanged()
        }
        fun add(data: T){
            datas.add(data)
            notifyDataSetChanged()
        }

        fun add(list: List<T>) {
            if (list.isEmpty()) return
            datas.addAll(list)
            notifyDataSetChanged()
        }

        fun clear() {
            if (datas.isEmpty()) return
            datas.clear()
            notifyDataSetChanged()
        }

        protected fun remove(t: T) {
            if (datas.isEmpty()) return
            datas.remove(t)
            notifyDataSetChanged()
        }

        protected fun remove(index: Int) {
            if (datas.isEmpty()) return
            datas.removeAt(index)
            notifyDataSetChanged()
        }

        fun getDatas(): List<T> {
            return datas
        }

        fun indexOf(data: T): Int {
            if (data == null) return -1
            return datas.indexOf(data)
        }

        fun size():Int{
            return datas.size?:0
        }

        fun getData(position: Int): T? {
            if (position < datas.size) return datas[position]
            return null
        }
    }

    abstract class BaseViewHolder<T, VDB : ViewDataBinding>(binding: VDB) :
        RecyclerView.ViewHolder(
            binding.root
        ) {
        var context: Context
            private set
        var data: T? = null
            private set
        var binding: VDB
            private set

        abstract fun onChange(data: T)

        fun update(data: T) {
            this.data = data
            onChange(data)
        }

        init {
            this.binding = binding
            this.context = this.binding.root.context
        }
    }
}
